package com.sdkj.fixed.asset.common.exception;

import com.sdkj.fixed.asset.common.base.BaseResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;


/**
 * 全局异常处理类
 */
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public Object handle(Exception ex) {
        if(ex instanceof LogicException){
            log.error("自定义异常信息："+ex.getMessage());
            return new BaseResultVo(100005,ex.getMessage());
        }
        if(ex instanceof MaxUploadSizeExceededException){
            log.error("附件大于10M超过最大值："+ex.getMessage());
            return new BaseResultVo(100006,"附件不得超过10M");
        }
        if(ex instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException exs = (MethodArgumentNotValidException) ex;
            BindingResult bindingResult = exs.getBindingResult();
            StringBuffer buffer = new StringBuffer();
            if (bindingResult.hasErrors()) {
                String errorMsg = bindingResult.getFieldError().getDefaultMessage();
                buffer.append(errorMsg);
            }
            log.error("参数校验失败：",buffer.toString());
            return new BaseResultVo(100001,buffer.toString());
        }else{
            log.error("服务异常",ex);
            return new BaseResultVo(120001,"系统异常");
        }
    }
}